package com.youi.third.wechat.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class WithdrawXmlUtil {

	 public WithdrawXmlUtil() {
	 }
	
	 //解析XML存入Map
	 public static Map doXMLParse(String strxml) throws JDOMException, IOException {
	        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
	        if (strxml != null && !"".equals(strxml)) {
	            Map m = new HashMap();
	            InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
	            SAXBuilder builder = new SAXBuilder();
	            Document doc = builder.build(in);
	            Element root = doc.getRootElement();
	            List list = root.getChildren();

	            String k;
	            String v;
	            for(Iterator it = list.iterator(); it.hasNext(); m.put(k, v)) {
	                Element e = (Element)it.next();
	                k = e.getName();
	                v = "";
	                List children = e.getChildren();
	                if (children.isEmpty()) {
	                    v = e.getTextNormalize();
	                } else {
	                    v = getChildrenText(children);
	                }
	            }

	            in.close();
	            return m;
	        } else {
	            return null;
	        }
	    }
	 
	 public static String getChildrenText(List children) {
	        StringBuffer sb = new StringBuffer();
	        if (!children.isEmpty()) {
	            Iterator it = children.iterator();

	            while(it.hasNext()) {
	                Element e = (Element)it.next();
	                String name = e.getName();
	                String value = e.getTextNormalize();
	                List list = e.getChildren();
	                sb.append("<" + name + ">");
	                if (!list.isEmpty()) {
	                    sb.append(getChildrenText(list));
	                }

	                sb.append(value);
	                sb.append("</" + name + ">");
	            }
	        }

	        return sb.toString();
	    }
		
}
